<template>
  <div>
    <el-dialog
      :title="title"
      :visible="showDialog"
      width="600px"
      center
      custom-class="my-dialog form-top"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="close"
    >
      <el-form
        ref="ruleForm"
        label-width="120px"
        :model="addList"
        :rules="rules"
      >
        <el-form-item label="物料名称" prop="name">
          <el-input
            v-model.trim="addList.name"
            placeholder="请输入物料名称（此为必填项）"
            style="width: 97%"
            size="small"
          />
        </el-form-item>
        <el-form-item label="规格型号" prop="model">
          <el-input
            v-model.trim="addList.model"
            placeholder="请输入规格型号（此为必填项）"
            style="width: 97%"
            size="small"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="预警数量" prop="warnCount">
          <el-input
            v-model.trim="addList.warnCount"
            placeholder="请输入预警数量"
            @input="message(addList.warnCount, '预警数量过长，请重新输入', 1)"
            style="width: 97%"
            size="small"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="单重" prop="singleWeight">
          <el-input
            v-model.trim="addList.singleWeight"
            placeholder="请输入单重"
            @input="message(addList.singleWeight, '单重过长，请重新输入', 2)"
            style="width: 97%"
            size="small"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="缩略图">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadImg"
            :on-change="changeImg"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <div v-else class="avatar-uploader-icon">
              <img src="~@/assets/material_img/uploadIcon.png" alt="" />
            </div>
          </el-upload>
        </el-form-item>
        <!-- 按钮 -->
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button
              class="dialog-btn"
              size="mini"
              type="primary"
              @click="addBtn"
            >
              确认
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  addMaterialList,
  editMaterialList,
  getMaterialDetail
} from '@/api/materialManage'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    title: String,
    id: [Number, String]
  },

  data() {
    return {
      addList: {
        name: '', // 物料名称
        model: '', // 规格型号
        warnCount: null, // 预警数量
        singleWeight: null, // 单重
        file: '' // 物料缩略图
      },
      imageUrl: '',
      rules: {
        name: [
          {
            required: true, // 必填项
            message: '物料名称不能为空', // 未通过校验的提示信息
            trigger: ['blur', 'change'], // 校验触发时机
          },
          {
            min: 1,
            max: 50,
            message: '物料名称输入长度过长！',
            trigger: ['blur', 'change'],
          }
        ],
        model: [
          {
            required: true,
            message: '规格型号不能为空',
            trigger: ['blur', 'change'],
          },
          {
            min: 1,
            max: 50,
            message: '规格型号输入长度过长！',
            trigger: ['blur', 'change'],
          }
        ],
        warnCount: [
          {
            pattern: /^[0-9]+(\.\d+)?$/,
            message: '只可输入大于等于0的数字',
            trigger: ['blur', 'change'],
          }
        ],
        singleWeight: [
          {
            pattern: /^[0-9]+(\.\d+)?$/,
            message: '只可输入大于等于0的数字',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  watch: {
    id: {
      async handler(val) {
        if (val != null) {
          const { result } = await getMaterialDetail({ id: val })
          this.addList = result
          this.imageUrl = result.imageBase64
        }
      }
    }
  },
  methods: {
    message(val, msg, type){
      if (val && val.length > 8) {
        // this.$message({
        //   type: 'error',
        //   message: msg,
        // })
        if (type === 1) {
          this.addList.warnCount = this.addList.warnCount.slice(0, 8)
        }
        if (type === 2) {
          this.addList.singleWeight = this.addList.singleWeight.slice(0, 8)
        }
      }
    },
    // 关闭弹窗清空所有值
    close() {
      this.$emit('update:showDialog', false)
      this.$emit('update:id', null)
      this.$refs.ruleForm.resetFields()
      this.addList = {
        name: '',
        model: '',
        warnCount: null,
        singleWeight: null,
        file: ''
      }
      this.imageUrl = ''
    },
    // 点击确认按钮
    addBtn() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.addList.id) {
            let formData = new FormData()
            formData.append('id', this.addList.id)
            formData.append('name', this.addList.name)
            formData.append('model', this.addList.model)
            formData.append('warnCount', this.addList.warnCount)
            formData.append('singleWeight', this.addList.singleWeight)
            formData.append('file', this.addList.file)
            await editMaterialList(formData)
            this.$message.success('修改成功！')
          } else {
            let formData = new FormData()
            formData.append('name', this.addList.name)
            formData.append('model', this.addList.model)
            formData.append('warnCount', this.addList.warnCount)
            formData.append('singleWeight', this.addList.singleWeight)
            formData.append('file', this.addList.file)
            await addMaterialList(formData)
            this.$message.success('新增成功！')

          }
          // 通知父组件重新请求部门列表数据
          this.$emit('updateList')
          this.$emit('update:showDialog', false)
        }
      })
    },
    handleAvatarSuccess() {
      this.$message.success('上传成功！')
    },
    beforeAvatarUpload(file) {
      const isImg = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/bmp'
      ].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImg) {
        this.$message.error('上传头像图片只能是 JPG PNG GIF BMP 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isImg && isLt5M
    },
    changeImg(file) {
      this.getBase64(file.raw).then((res) => {
        this.imageUrl = res
      })
    },
    // 将文件流转化成base64
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    },
    // 自定义上传图片
    uploadImg(files) {
      this.addList.file = files.file
    }
  }
}
</script>
<style lang="scss">
@import '~@/styles/_handle.scss';
.avatar-uploader .el-upload {
  @include background('upload_btn_bg_color');
}
</style>
<style scoped lang="scss">
@import '~@/styles/_handle.scss';
.el-row {
  text-align: center;
}
.imageBox,
.uploadBtn {
  width: 64px;
  height: 64px;
  background-color: #fff;
  -webkit-clip-path: polygon(
    15% 0,
    85% 0,
    100% 15%,
    100% 85%,
    85% 100%,
    15% 100%,
    0 85%,
    0 15%
  );
  clip-path: polygon(
    15% 0,
    85% 0,
    100% 15%,
    100% 85%,
    85% 100%,
    15% 100%,
    0 85%,
    0 15%
  );
}
.uploadBtn {
  display: flex;
  align-items: center;
  justify-content: center;

  img {
    width: 32px;
    height: 32px;
  }
}
.dialog-btn {
  margin-top: 10px;
  font-size: 18px;
  height: 40px;
}
::v-deep .avatar-uploader .el-upload {
  width: 64px;
  height: 64px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  -webkit-clip-path: polygon(
    10px 0,
    calc(100% - 10px) 0,
    100% 10px,
    100% calc(100% - 10px),
    calc(100% - 10px) 100%,
    10px 100%,
    0 calc(100% - 10px),
    0 10px
  );
  clip-path: polygon(
    10px 0,
    calc(100% - 10px) 0,
    100% 10px,
    100% calc(100% - 10px),
    calc(100% - 10px) 100%,
    10px 100%,
    0 calc(100% - 10px),
    0 10px
  );
  .avatar-uploader-icon {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 64px;
    height: 64px;
  }
  .avatar {
    width: 64px;
    height: 64px;
    display: block;
  }
}

::v-deep .el-input--small .el-input__inner {
  // @include form_input_color('form_top_bg_color');
  height: 48px;
  line-height: 48px;
  font-size: 18px;
}
::v-deep .el-form-item__label {
  font-size: 18px;
  color: #fff;
  line-height: 48px;
  font-weight: normal;
  padding-left: 20px;
  text-align-last: justify;
}
::v-deep .el-form-item:nth-child(n + 3) {
  .el-form-item__label {
    padding-left: 30px;
  }
}
</style>
